package com.wjp.dinosaur.handler;

import com.alibaba.fastjson.JSON;
import com.wjp.dinosaur.dao.pojo.User;
import com.wjp.dinosaur.service.LoginService;
import com.wjp.dinosaur.vo.ErrorCode;
import com.wjp.dinosaur.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置响应编码UTF-8
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");

        // 获取header里的token
//        String token = request.getHeader("token");
        String token = request.getParameter("token");
        System.out.println("获取到的token "+token);

        // 如果不是常规的GET或者POST请求直接放行
        String method = request.getMethod();
        if (!method.equalsIgnoreCase("GET")&&!method.equalsIgnoreCase("POST")){
            return true;
        }



        // 跨域请求options返回为空
        String str = "OPTIONS";
        if (str.equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            System.out.println("跨域请求options返回为空");
            return false;
        }// 除了options跨域请求，都进入到jwt校验
        else{
            if (token == null){
                Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }
            // 校验接口传进来的token信息
            User user = loginService.checkToken(token);
            if (user == null){
                Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }
            // 如果是登录状态就放行
            System.out.println("登录成功");
            return true;
        }

    }
}
